﻿/*==========================================
    *   程序说明: 防止HttpPost重复提交
    *   作者姓名: xp
    *   创建日期: 2106-05-12
    *   最后修改: 
    *   
    *   注: 
    *   版权所有特友 http://o2o.teshehui.com       
 ==========================================*/

using System;
using System.Web.Mvc;
using TY.UC.Log4;

namespace TY.UI.Mvc.Extension.ReSubmit
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class ValidateReHttpPostTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public PageTokenViewBase PageTokenView { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidateReHttpPostTokenAttribute"/> class.
        /// </summary>
        public ValidateReHttpPostTokenAttribute()
        {
            //It would be better use DI inject it.
            PageTokenView = new SessionPageTokenView();
        }

        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            try
            {
                if (filterContext == null)
                {
                    throw new ArgumentNullException("filterContext");
                }
                if (!PageTokenView.TokensMatch)
                {
                    //log...
                    throw new Exception("Invaild Http Post!");
                }
            }
            catch(Exception e)
            {
                Log4NetHelper.WriteLog("ValidateReHttpPostTokenAttribute-OnAuthorization", e);
            }
        }
    }
}
